// pages/registration/entrance.js
var Constant = require('../../utils/constant.js');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    array: ['居民身份证', '临时身份证'], 
    wordTypeList: ['就业', '个体',"自由职业","就学","在家居住"],
    // roleList: ['业主', '租客', "物业", "快递", "装修", "外卖", "送水员", "送奶员", "其他"],
    roleList: [],
    communityList: [],
    buildNumList: ['第1栋', '第2栋', "第3栋"],
    unitList: ['第1单元', '第2单元'],
    userName: '',
    sex: 0,
    cardType: '居民身份证',
    cardNumber: '',
    phoneNum: '',
    code: '',
    serverCode: '',
    serverPhoneNum: '',
    workStatus: 0,
    role: '业主', 
    community: '请选择小区',
    buildNum: '请选择楼栋',
    unit: '请选择单元',
    wordType: '就业',
    buildShow: false,
    unitShow:false,
    time: '获取验证码', //倒计时 
    currentTime: 30,
    disabled: false,
    persondoorno: '',
    hourseNum: '',
    unitno: '',
    buildno: '',
    communityno: '',
    typecode:'',
    picBase64: '',
    takePicType: 'entrance',
    isEntrance:true,
    departcode: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.globalData.orgCode != "") {
      this.setData({
        departcode: app.globalData.orgCode,
      })
    }
    this.setData({
      userName: app.globalData.username,
      cardNumber: app.globalData.idcard
    })
    getLocation(this);
    // var scene = decodeURIComponent(options.scene)//参数二维码传递过来的参数
    // console.log(options.query)
    // var querycode = options.query.departcode // 参数二维码传递过来的场景参数
    // if (querycode){
    //   this.setData({
    //     departcode: querycode,
    //   })
    // }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    if (app.globalData.openid == "") {
      wx.showModal({
        title: '提示',
        content: '用户未登录无法注册业主',
        showCancel: false,
        success: function () {
          wx.navigateBack({
            delta: 2,
          })
        }
      })
    }
    console.log(app)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },


  getCode: function (options) {
    var that = this;
    var currentTime = that.data.currentTime;
    var interval = setInterval(function () {
      currentTime--;
      that.setData({
        time: currentTime + '秒'
      })
      if (currentTime <= 0) {
        clearInterval(interval)
        that.setData({
          time: '获取验证码',
          currentTime: 60,
          disabled: false
        })
      }
    }, 1000)
  },
  getVerificationCode() {
    var phone = this.data.phoneNum;
    var that = this;
    
    if (!(/^1[34578]\d{9}$/.test(phone))) {
      wx.showToast({
        title: '手机号码有误，请重填',
        icon: 'none',
      })
      return;
    } 
    that.setData({
      disabled: true,
    })
    wx.request({
      url: Constant.BASEURL + Constant.PHONE_CODE_URL + phone,
      method: 'GET',
      success: function (res) {
        console.log(res.data)
        that.getCode();
        that.setData({
          serverCode: res.data.param,
          serverPhoneNum: res.data.personphone,
        })
      },
      fail: function (res) {
        that.setData({
          disabled: false,
        })
        wx.showToast({
          title: '获取验证码失败',
          icon: 'none'
        })
      },
      complete: function (res) {
        console.log(res)
      }
    })

    
  },

  radioChange: function(e){
    console.log('radio发生change事件，携带value值为：', e.detail.value)
  },

  userName: function (e) {
    this.setData({
      userName: e.detail.value
    })
  },

  idCard: function (e){
    this.setData({
      cardNumber: e.detail.value
    })
  },

  checkIdCard: function(event){
    console.log("idcard", event.detail.value)
    if (!Constant.idCard(event.detail.value)) {
      wx.showToast({
        title: '证件号不正确',
        icon: 'none',
      })
    }
  },

  phoneNum: function (e) {
    this.setData({
      phoneNum: e.detail.value
    })
  },

  code: function (e) {
    this.setData({
      code: e.detail.value
    })
  },
  hourseNum: function(e){
    this.setData({
      hourseNum: e.detail.value
    })
  },

  bindWorkChange: function(e){
    this.setData({
      wordType: this.data.wordTypeList[e.detail.value],
    })
  },
  bindCardTypeChange: function (e){
    this.setData({
      cardType: this.data.array[e.detail.value],
    })
    
  },
  bindRoleChange: function(e){
    this.setData({
      role: this.data.roleList[e.detail.value].typename,
      typecode: this.data.roleList[e.detail.value].typecode,
    })
  },
  bindCommunityChange: function (e) {
    console.log(e)
    this.setData({
      community: this.data.communityList[e.detail.value].departname,
      communityno: this.data.communityList[e.detail.value].org_code,
      buildNumList: this.data.communityList[e.detail.value].children,
    })
    
    if(this.data.buildNumList.length > 0){
      this.setData({
        buildShow: true,
      })
    }
  },
  bindBuildChange: function (e) {
    this.setData({
      buildNum: this.data.buildNumList[e.detail.value].departname,
      buildno: this.data.buildNumList[e.detail.value].org_code,
      unitList: this.data.buildNumList[e.detail.value].children,
    })

    if (this.data.unitList.length > 0) {
      this.setData({
        unitShow: true,
      })
    }

  },
  bindUnitChange: function (e){
    this.setData({
      unit: this.data.unitList[e.detail.value].departname,
      unitno: this.data.unitList[e.detail.value].org_code,
    })
    
  },
 
  buttonNext:function(e){
    var that = this;
    if (that.data.userName == '') {
      wx.showToast({
        title: '没有填写姓名',
        icon: 'none',
      })
      return;
    }

    if (!Constant.idCard(that.data.cardNumber)) {
      wx.showToast({
        title: '证件号不正确',
        icon: 'none',
      })
      return;
    }

    if (that.data.code == '') {
      wx.showToast({
        title: '没有填写验证码',
        icon: 'none',
      })
      return;
    } else {
      if (that.data.serverCode != that.data.code || that.data.serverPhoneNum != that.data.phoneNum) {
        console.log("服务端验证码：", that.data.serverCode, "用户输入的验证码：", that.data.code)
        console.log("服务端手机号：", that.data.serverPhoneNum, "用户输入的手机号：", that.data.phoneNum)
        wx.showToast({
          title: '验证码不正确',
          icon: 'none',
        })
        return;
      }
    }

    if (that.data.community == '请选择小区') {
      wx.showToast({
        title: '没有选择小区',
        icon: 'none',
      })
      return;
    }
    if (that.data.buildNum == '请选择楼栋') {
      wx.showToast({
        title: '请选择楼栋',
        icon: 'none',
      })
      // that.data.buildno = that.data.communityno;
      // that.data.buildNum = '';
      return;
    }
    if (that.data.unit == '请选择单元') {
      // that.data.unitno = that.data.buildno;
      // that.data.unit = '';
      wx.showToast({
        title: '请选择单元',
        icon: 'none',
      })
    }
    var location = that.data.community + that.data.buildNum + that.data.unit; 

    wx.request({
      url: Constant.BASEURL + Constant.CHECK_YEZHU,
      method: "POST",
      data: {
        "unitno": that.data.unitno,
        "persondoorno": that.data.hourseNum, 
        "personidcardno": that.data.cardNumber,
        "openid":app.globalData.openid
      },
      success: function (res) {
        console.log("请求完成",res.data)
        //该户业主已有人申请，正在审核中
        if(res.data.state == 1){
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
          })        
        }
        //您已被该户业主添加为亲属，无需进行下一步注册！
         else if (res.data.state == 2){
          Constant.STATE_USER = Constant.STATE_USER_ISRELATIVES;
          // wx.showToast({
          //   title: res.data.msg,
          //   icon: 'none'
          // })

          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            success: function(res) {
              wx.navigateBack({
                delta: -1
              })
            },
          })
        }
        //您已经在平台被注册过业主，已自动转为业主！
         else if (res.data.state == 3){
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
          })        
        }
        //该户已存在业主，请联系业主进行亲属添加！
        else if (res.data.state == 4){
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
          })       
        }
        //可以注册
        else{
          wx.navigateTo({
              url: '../takephoto/takephoto?personname=' + that.data.userName
                + "&personidcardno=" + that.data.cardNumber
                + "&personphoneno=" + that.data.phoneNum
                + "&persondoorno=" + that.data.hourseNum
                + "&unitno=" + that.data.unitno
                + "&persontype=" + '1'
                + "&sex=" + that.data.sex
                + "&cardType=" + that.data.cardType
                + "&wordType=" + that.data.wordType
                + "&role=" + '业主'
                + "&location=" + location
                + "&community=" + that.data.community
                + "&buildNum=" + that.data.buildNum
                + "&takePicType=" + that.data.takePicType
            })
        }
      },
      fail:function(err){
        wx.showToast({
          title: '请求失败，检查网络状态',
          icon: 'none'
        })
      }
    })
  },
})
 
var typeList = [];
function getLocation(that){
  wx.request({
    url: Constant.BASEURL + Constant.ALLLIST_URL,
    method: 'GET',
    success: function (res) {
      console.log(res.data)
      typeList = res.data.data.typeList;
      if (res.data.data.typeList.length == 3) {
        typeList = res.data.data.typeList
        
      }
      that.setData({
        roleList: res.data.data.typeList[0],
        communityList: res.data.data.departlist
      })
      //遍历小区查询 如果有code相同的就自动填写
      for (var i = 0; i < that.data.communityList.length; i++) {
        var org_code = that.data.communityList[i].org_code;
        var name = that.data.communityList[i].departname;
        var buildList = that.data.communityList[i].children;
        if (org_code == that.data.departcode) {
          that.setData({
            community: name,
            buildShow: true,
            communityno: org_code,
            buildNumList: buildList,
          })
        }
      }
    }
  })
}
function isCardNo(card) {
  // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X 
  var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  if (reg.test(card) === false) {
    return false;
  }
  return true;
}
